package com.dankegongyu.component.jsbridge.jsbridge;

import android.graphics.Bitmap;

import com.dankegongyu.component.jsbridge.listener.DKWebViewClientCallback;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * 如果要自定义WebViewClient必须要集成此类
 * Created by bruce on 10/28/15.
 */
public class BridgeWebViewClient extends WebViewClient {

    private BridgeWebView webView;
    private DKWebViewClientCallback callback;

    public BridgeWebViewClient(BridgeWebView webView, DKWebViewClientCallback callback) {
        this.webView = webView;
        this.callback = callback;
    }

    @Override
    public final boolean shouldOverrideUrlLoading(WebView view, String url) {
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (url.startsWith(BridgeUtil.YY_RETURN_DATA)) { // 如果是返回数据
            webView.handlerReturnData(url);
            return true;
        } else if (url.startsWith(BridgeUtil.YY_OVERRIDE_SCHEMA)) { //
            webView.flushMessageQueue();
            return true;
        } else if (callback != null) {
            return callback.shouldOverrideUrlLoading(view, url);
        } else {
            return super.shouldOverrideUrlLoading(view, url);
        }
    }

    // 增加shouldOverrideUrlLoading在api》=24时
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        String url = request.getUrl().toString();
        if (request != null) {
            url = request.getUrl().toString();
        }
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        if (url.startsWith(BridgeUtil.YY_RETURN_DATA)) { // 如果是返回数据
            webView.handlerReturnData(url);
            return true;
        } else if (url.startsWith(BridgeUtil.YY_OVERRIDE_SCHEMA)) { //
            webView.flushMessageQueue();
            return true;
        } else if (callback != null) {
            return callback.shouldOverrideUrlLoading(view, url);
        } else {
            return super.shouldOverrideUrlLoading(view, request);
        }
//        } else {
//            if (callback != null) {
//                return callback.shouldOverrideUrlLoading(view, request);
//            }
//            return super.shouldOverrideUrlLoading(view, request);
//        }
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        if (callback != null) {
            callback.onPageStarted(view, url, favicon);
        }
    }

    @Override
    public void onPageFinished(WebView view, String url) {

        super.onPageFinished(view, url);

        // bugly 监听 webview crash
//        InitSdkConfig initSdkConfig = InitSdkService.getInstance().getSdkConfig();
//        if (initSdkConfig.getInitBuglyData() != null && initSdkConfig.getInitBuglyData().isJavascriptMonitor()) {
//            CrashReport.setJavascriptMonitor(new DKCrashReport(webView), true);
//        }

//        if (BridgeWebView.toLoadJs != null) {
//            BridgeUtil.webViewLoadLocalJs(view, BridgeWebView.toLoadJs);
//        }

        //
        if (webView.getStartupMessage() != null) {
            for (Message m : webView.getStartupMessage()) {
                webView.dispatchMessage(m);
            }
            webView.setStartupMessage(null);
        }

        if (callback != null) {
            callback.onPageFinished(view, url);
        }
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        if (callback != null) {
            callback.onReceivedError(view, errorCode, description, failingUrl);
        }
    }

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        // webView默认是不处理https请求的，页面显示空白，需要进行如下设置
        // handler.proceed(); // 表示等待证书响应
        // handler.cancel(); // 表示挂起连接，为默认方式
        // handler.handleMessage(null); // 可做其他处理
        if (callback != null) {
            callback.onReceivedSslError(view, handler, error);
        }
    }

    @Override
    public void onFormResubmission(WebView view, android.os.Message dontResend, android.os.Message resend) {
        // 有的时候，在程序中的webview在调用goBack()方法时，不起作用。
        // 这时候可能是这个web页面是一个表单提交的结果页，这时需要重载onFormResubmission
        resend.sendToTarget();
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        if (callback != null) {
            return callback.shouldInterceptRequest(view, url);
        }
        return null;
    }

}